package com.ctg.behavior.calc.impala.transfer;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.utils.CtCalcSQLUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcRestrict;
import com.ctg.behavior.common.consts.CtFunctionConsts;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtTimeRestrictTransfer implements CtSQLTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtCalcRestrict)) {
			log.warn("calcObject is not CtCalcRestrict, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			return "";
		}
		CtCalcRestrict restrict = (CtCalcRestrict) calcObject;
		log.info("CalcBody={}", JSON.toJSONString(restrict));

		StringBuilder impalaSQL = new StringBuilder();
		impalaSQL.append(" ( ");

		if (CtFunctionConsts.KEY_ABSOLUTE_TIME.equalsIgnoreCase(restrict.getFunction())) {
			// 1.绝对时间
			String fromDate = restrict.getParams().get(0);
			String toDate = restrict.getParams().get(1);
			// impalaSQL.append(" event_date >= '").append(fromDate).append("' ");
			// impalaSQL.append(" AND event_date <= '").append(toDate).append("' ");
			String field = CtCalcSQLUtils.fillAlias("event_date", sqlParam);
			impalaSQL.append(field).append(" >= '").append(fromDate).append("' ");
			impalaSQL.append(" AND ");
			impalaSQL.append(field).append(" <= '").append(toDate).append("' ");
		} else if (CtFunctionConsts.KEY_RELATIVE_TIME.equalsIgnoreCase(restrict.getFunction())) {
			// 2.相对时间

		} else if (CtFunctionConsts.KEY_DYNAMIC_TIME.equalsIgnoreCase(restrict.getFunction())) {
			// 3.动态时间

		}

		impalaSQL.append(" ) ");

		String retSQL = impalaSQL.toString();
		log.info("CalcSQL={}", impalaSQL);

		return retSQL;
	}

}
